#!/bin/sh
#
# parallel import sql file
#
# 2022-11-02: Created by yike
#

# vi tasklist
# database -> sql_file with out ext
# gsp_order -> od_mat_sale_bill_item
# gsp_order -> od_mat_sale_bill

function para_init() {
    tempfifo="my_temp_fifo"
    mkfifo ${tempfifo}
    exec 6<>${tempfifo}
    rm -f ${tempfifo}
    for ((i = 1; i <= ${thread_num}; i++)); do
        echo
    done >&6
}

function para_run() {
    OLD_IFS=$IFS
    IFS=$'\n'
    i=0
    # for task in $1; do
    #     i=$((i+1))
    #     read -u6
    #     {
    #         printf "%s: [%02d] Doing %s\n" "$(date '+%Y-%m-%d %H:%M:%S')" "$i" "$task"
    #         para_stask "$task"
    #         printf "%s: [%02d] Done  %s\n" "$(date '+%Y-%m-%d %H:%M:%S')" "$i" "$task"
    #         echo "" >&6
    #     } &
    # done
    total=$(echo "$1" | wc -l)
    while true; do
        # 取一个已经传输完了的文件
        file=$(ls -l exp*.log 2>/dev/null | head -n1 | awk '{print $NF}')
        if [ "$file" != "" ]; then
            i=$((i + 1))
            mv $file ${file}.doing
            tmp=$(echo $file | sed 's/^exp_//' | sed 's/.log$//')
            task=$(echo "$1" | grep " ${tmp}$")
            read -u6
            {
                printf "%s: [%02d] Doing %s\n" "$(date '+%Y-%m-%d %H:%M:%S')" "$i" "$task"
                para_stask "$task"
                printf "%s: [%02d] Done  %s\n" "$(date '+%Y-%m-%d %H:%M:%S')" "$i" "$task"
                mv ${file}.doing ${file}.done
                rm -f ${tmp}.sql
                echo "" >&6
            } &

        else
            sleep 5
        fi

        if [ $i -eq $total ]; then
            break
        fi
    done
    IFS=$OLD_IFS
    wait
    exec 6>&-
}

# 任务函数
function para_stask() {
    database=$(echo $1 | awk -F' -> ' '{print $1}')
    sqlfile=$(echo $1 | awk -F' -> ' '{print $2}')
    # mysql -uroot -p'3eDB_Adm$' -D ${database} < ${sqlfile}.sql > imp_${sqlfile}.log 2>&1
    echo "${database} -> ${sqlfile}"
    sleep 2
}

function main() {
    tasklist=$(cat tasklist | grep -v '^#') # 任务列表
    thread_num=4                            # 并发数
    para_init "$thread_num"
    para_run "$tasklist"
}

echo "$(date '+%Y-%m-%d %H:%M:%S'): Begin"
main
echo "$(date '+%Y-%m-%d %H:%M:%S'): Done"
